package com.framework.module_google

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.util.Log
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.BeginSignInRequest.GoogleIdTokenRequestOptions
import com.google.android.gms.auth.api.identity.BeginSignInRequest.PasswordRequestOptions
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.Scope
import com.google.api.services.drive.DriveScopes

/**
 * @author: HeXinGen
 * @date: 2024/1/4
 * @descption:
 *
 *
 * 谷歌登录分为：
 * 1.授权登录
 * 2.一键登录
 *
 *
 * 这里使用的凭证必须是web 凭证，使用android 凭证无法获取登录成功
 *
 *
 * 使用文档：
 *
 * 谷歌一键登录：https://developers.google.com/identity/one-tap/android/overview?hl=zh-cn
 * https://juejin.cn/post/7024375507978289166
 * https://blog.csdn.net/Android_yh/article/details/129352068
 */
class GoogleLogin {


    // android 多个环境的凭证
    val android_id_test = "90517965910-omhnoqrbmbeeeg07fbes8bl6nu3esf47.apps.googleusercontent.com"

    // val android_id_release = "90517965910-s3muthb2c11l7s2k71i0n00hb9ttot2n.apps.googleusercontent.com"
    // val android_id_pre_release = "90517965910-6oidd4aept8kdrpg4vaofr476qlrhofn.apps.googleusercontent.com"
    //web的凭证
    val web_id = ""

    private val webIds =
        mapOf(
            "com.kai.bitchat.test" to "90517965910-6ea96itocvh18ldn7mfbnjb5j953ga89.apps.googleusercontent.com",
            "com.kai.bitchat" to "90517965910-s3muthb2c11l7s2k71i0n00hb9ttot2n.apps.googleusercontent.com",
            "com.bitchat.android"  to "90517965910-6ea96itocvh18ldn7mfbnjb5j953ga89.apps.googleusercontent.com"
//            "com.bitchat.android"  to "90517965910-hr6m8oaae7em6lc9084oqnvqsa7eq43j.apps.googleusercontent.com"
        )


    /**
     * 谷歌授权登录
     * 调用谷歌登录api,会弹窗提示：用户选择账号验证成功后，会在ActivityResult中回调有关于谷歌账号的信息。
     */
    fun authorizedLoginAndroidx(activity: AppCompatActivity, callback: GoogleSignListener) {
        val launcher =
            activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                handleGoogleSignIntent(request_google_login_sign, it.resultCode, it.data, callback)
            }
        launcher.launch(createGoogleSignIntent(activity))
    }

    /**
     * 构建谷歌登录的intent
     */
    private fun createGoogleSignIntent(activity: Activity): Intent {
        Log.e("Jxr.GoogleLogin", "createGoogleSignIntent.. package: ${activity.packageName}, key: ${webIds[activity.packageName]}")
        val signInOptions = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestScopes(Scope(DriveScopes.DRIVE_FILE)) //指定访问空间，这里是云盘drive
            .requestIdToken(webIds[activity.packageName]!!)//这里使用android 凭证无法获取,必须使用web 凭证。
            .build()
        val client = GoogleSignIn.getClient(activity, signInOptions)
        return client.signInIntent;
    }

    fun signout(activity: Activity) {
        val signInOptions = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(webIds[activity.packageName]!!)//这里使用android 凭证无法获取,必须使用web 凭证。
            .build()
        val client = GoogleSignIn.getClient(activity, signInOptions)
        client.signOut()
    }

    /**
     * 谷歌授权登录
     * 兼容flutterActivity非androidX的AppCompatActivity
     */
    fun authorizedLogin(activity: Activity) {
        activity.startActivityForResult(createGoogleSignIntent(activity), request_google_login_sign)
    }

    companion object {
        val request_google_login_sign = 886
    }


    /**
     * 使用谷歌一键登录:
     *  该方法无法获取到谷歌邮箱, 暂未使用
     * https://developers.google.com/identity/one-tap/android/get-saved-credentials?hl=zh-cn
     */
    @SuppressLint("SuspiciousIndentation")
    fun oneKeyAuthorizedLogin(activity: AppCompatActivity, callback: GoogleSignListener) {
        val oneTapClient = Identity.getSignInClient(activity)
        val launcher =
            activity.registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) {
                if (it.resultCode == Activity.RESULT_OK) {
                    if (it.data == null) {
                        callback.error(java.lang.Exception("request google sign fair： return data is null"))
                        return@registerForActivityResult
                    }
                    val signInCredential = oneTapClient.getSignInCredentialFromIntent(it.data)
                    LogUtils.printI(" google one key success: ${signInCredential.id}  ${signInCredential.googleIdToken} ${signInCredential.displayName}")
                } else {
                    callback.error(java.lang.Exception("request google sign fair: ${it.resultCode}"))
                }
            }
        var signInRequest = BeginSignInRequest.Builder()
            //设置密码
            .setPasswordRequestOptions(PasswordRequestOptions.builder().setSupported(true).build())
            //设置凭证
            .setGoogleIdTokenRequestOptions(
                GoogleIdTokenRequestOptions.Builder()
                    .setSupported(true)
                    .setServerClientId(webIds[activity.packageName]!!)
                    .setFilterByAuthorizedAccounts(true)
                    .build()
            )
            // 设置自动选择凭证的用户
            .setAutoSelectEnabled(true)
            .build()
        oneTapClient.beginSignIn(signInRequest)
            .addOnSuccessListener {
                LogUtils.printI("beginSignIn success")
                launcher.launch(IntentSenderRequest.Builder(it.pendingIntent.intentSender).build())
            }.addOnFailureListener {
                callback.error(java.lang.Exception("Unable to sign in.", it))
            }
    }

    /**
     * 该函数使用在谷歌drive云盘上传文件，前的谷歌授权登录。
     */
    fun loginGoogleEmailAndGoogleDrive(activity: AppCompatActivity, callback: GoogleSignListener) {
        val launcher =
            activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == Activity.RESULT_OK) {
                    if (it.data == null) {
                        callback.error(java.lang.Exception("request google sign fair： return data is null"))
                        return@registerForActivityResult
                    }
                    handleGoogleEmail(it.data!!, callback)

                } else {
                    callback.error(java.lang.Exception("request google sign fair: ${it.resultCode}"))
                }
            }
        val signInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestScopes(Scope(DriveScopes.DRIVE_FILE)) //指定访问空间，这里是云盘drive
            .build()
        val client = GoogleSignIn.getClient(activity, signInOptions)
        launcher.launch(client.signInIntent)
    }

    /**
     * 处理Activity#onActivityResult()中返回结果。
     *
     */
    fun handleGoogleSignIntent(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
        callback: GoogleSignListener
    ) {
        if (requestCode != request_google_login_sign) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                callback.error(java.lang.Exception("request google sign fair： return data is null"))
                return
            }
            handleGoogleEmail(data!!, callback)
        } else {
            callback.error(java.lang.Exception("request google sign fair: $resultCode"))
        }
    }

    private fun handleGoogleEmail(intent: Intent, callback: GoogleSignListener) {
        GoogleSignIn.getSignedInAccountFromIntent(intent)
            .addOnSuccessListener {
                callback.success(it)
            }
            .addOnFailureListener {
                callback.error(java.lang.Exception("Unable to sign in.", it))
            }
    }


    interface GoogleSignListener {

        /**
         * 谷歌登录成功
         */
        fun success(googleSignInAccount: GoogleSignInAccount)

        /**
         * 谷歌登录失败
         */
        fun error(error: Exception)
    }
}